from django.http import JsonResponse, HttpResponse
from rest_framework.parsers import JSONParser
from .serializers import UserInfoSerializer
from .models import UserInfo


def user_list(request):
    """
    get获取用户列表
    post添加用户信息
    """
    if request.method == "GET":
        # 获取信息
        # 查询所有用户信息
        users = UserInfo.objects.all()
        # 创建序列化器对象
        ser = UserInfoSerializer(users, many=True)

        result = {
            "data": ser.data,
            "code": 200,
            "message": "ok",
        }
        return JsonResponse(result, safe=True)
    elif request.method == "POST":
        # 添加一条信息
        params = JSONParser().parse(request)
        ser = UserInfoSerializer(data=params)
        if ser.is_valid():
            ser.save()
            return JsonResponse({'code': 201, "data": ser.data,"message": "ok"}, status=201)
        else:
            return JsonResponse({'code': 400, "message": ser.errors}, status=400)
    else:
        return JsonResponse({'code': 405, "message": '当前地址不支持该请求方法'.format(request.method)}, status=405)


def user_detail(request,id):
    try:
        obj = UserInfo.objects.get(id=id)
    except Exception as e:
        return HttpResponse('404!访问资源不存在',  status=404)

    if request.method == "GET":
        ser = UserInfoSerializer(obj)
        return JsonResponse({'code': 201, "data": ser.data,"message": "ok"}, status=201)
    elif request.method == "DELETE":
        obj.delete()
        return JsonResponse({'code': 204, "message": "删除成功"}, status=204)
    elif request.method == "PUT":
        params = JSONParser().parse(request)
        ser = UserInfoSerializer(instance=obj, data=params)
        if ser.is_valid():
            ser.save()
            return JsonResponse({'code': 201, "data": ser.data, "message": "ok"}, status=201)
        else:
            return JsonResponse({'code': 400, "message": ser.errors}, status=400)
    else:
        return JsonResponse({'code': 405, "message": '当前地址不支持该请求方法'.format(request.method)}, status=405)

